package bTree.LeetCode;

import java.util.Arrays;

public class 下一个更大元素3 {
    public int nextGreaterElement(int n) {
        char[] charArray = Integer.toString(n).toCharArray();
        int length = charArray.length;
        int cnt=1;
        for (int i=0;i<length-1;i++){
            if (charArray[i]>=charArray[i+1]){
                cnt++;
            }
        }
        if (cnt==length){
            return -1;
        }
        for (int i=length-1;i>=0;i--){
            for (int j=length-1;j>i;j--){
                if (charArray[j]>charArray[i]){
                    char temp=charArray[j];
                    charArray[j]=charArray[i];
                    charArray[i]=temp;
                    Arrays.sort(charArray, i+1, length);
                    long l = Long.parseLong(new String(charArray));
                    if (l>Integer.MAX_VALUE){
                        return -1;
                    }
                    return Integer.parseInt(new String(charArray));
                }
            }
        }
        return -1;
    }
}